package GameConfig

import (
	xml "misc/dom4g"
	log "misc/seelog"
	"os"
	"strconv"
	cfg "utils/config"
)

const weaponXmlPath = "GameCore/Weapons.xml"

var xmlWeaponsMap map[string]*XmlWeapon

type XmlWeapon struct {
	Desc        string
	AttackSpeed float64
	Name        string

	EffectName       string
	BeforeAttackRoll float64
}

func GetXmlWeapon(weaponName string) *XmlWeapon {
	return xmlWeaponsMap[weaponName]
}

func loadXmlWeapon() {
	path := cfg.Get()["GameConfigPath"] + weaponXmlPath
	xmlWeaponsMap = make(map[string]*XmlWeapon)
	f, err := os.Open(path)
	if err != nil {
		log.Info(err)
	}
	xmldoc, err2 := xml.LoadByStream(f)
	if err2 != nil {
		log.Info(err2)
	}

	for _, v := range xmldoc.Root().AllNodes() {
		weapon := parseXmlWeapon(v)
		xmlWeaponsMap[weapon.Name] = weapon
	}
}

func parseXmlWeapon(node *xml.Element) *XmlWeapon {
	weapon := &XmlWeapon{}
	weapon.Name, _ = node.AttrValue("Name")
	weapon.Desc, _ = node.AttrValue("Desc")
	attackSpeed, _ := node.AttrValue("AttackSpeed")
	weapon.AttackSpeed, _ = strconv.ParseFloat(attackSpeed, 32)

	if strBfAttackRoll, ok := node.AttrValue("BeforeAttackRoll"); ok {
		weapon.BeforeAttackRoll, _ = strconv.ParseFloat(strBfAttackRoll, 32)
	}

	if effectName, ok := node.AttrValue("EffectName"); ok {
		weapon.EffectName = effectName
	}

	return weapon
}
